const express = require('express')
const router = express.Router()
const ip = require('ip')

// 获取ip地址
router.get('/ip', (req, res) => {
  let curIp = req.headers['x-forwarded-for'] ||
  req.connection.remoteAddress ||
  req.socket.remoteAddress ||
  req.connection.socket.remoteAddress;
  // console.log(curIp, 'curIp')
  // 当为localhost、127.0.0.1访问时，为本地ip地址
  if(curIp.includes('::1') || curIp.includes('127.0.0.1')) {
    curIp = ip.address()
  } else {
    const arr = /\d+\.\d+\.\d+\.\d+/.exec(curIp)
    curIp = arr ? arr[0] : ''
  }
  res.send(curIp)
})

module.exports = router
